package com.example.demo.error;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;

/*
 * @Author:大力王
 * @Date:2024/3/31-31-17:06
 * 开始了
 */
@Component
public class HttpRequestFilte implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        String method = httpRequest.getMethod();
        if (!isValidHttpMethod(method)) {
            method = "GET"; // 将不合法的请求方法转换为GET方法
        }

        String finalMethod = method;
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(httpRequest) {
            @Override
            public String getMethod() {
                return finalMethod;
            }
        };

        filterChain.doFilter(requestWrapper, servletResponse);
    }

    private boolean isValidHttpMethod(String method) {
        return "GET".equalsIgnoreCase(method) || "POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method)
                || "DELETE".equalsIgnoreCase(method) || "OPTIONS".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method);
    }
}
